$(function () {
  /**
   * @param {int} a 闪烁剩余次数
   * @param {int} speed 闪烁速度，值越小越快
   */
  $.fn.flash = function (a, speed = 500) {
    a -= 1;
    const $this = $(this);
    const lstA = $this.data('lstA') || a + 1;
    // console.log("a", a);
    const fnToggleClass = (arg) => {
      // console.log("arg", arg);
      $this.css("display") == "none" && $this.toggleClass('flash');
    };
    fnToggleClass(lstA);
    $this.animate({ opacity: "toggle" }, speed, function () {
      $this.css("display") == "none" && $this.flash(-1, speed);
    });
    if (a > -1) {
      $this.data('lstA', a);
    }
    a > 0 && $(this).flash(a, speed);
  };

  const arrLogKeysForDedup = LogKeysForDedup.split(',').map(item => item.trim());
  const edtID = $("#edtID").val();
  const _edtTitle = () => $("#edtTitle").val().trim();

  console.log("用于检查重复的字段：", arrLogKeysForDedup.join(','));
  console.log("当前编辑文章 ID：", edtID);

  const fnRltAddOrReset = ($arg = null) => {
    // console.log($arg);
    // console.log(typeof $arg);
    if ($arg !== null) {
      // 移除上一次结果
      $(".meta-rlt").remove();
      $("#divEditForm1").after($arg);
    } else {
      $(".meta-rlt").html("等待中...");
    }
  }

  const $$inpMetaForDedup = {};
  let t, $inpMeta;
  arrLogKeysForDedup.forEach(function (metaKey) {
    if (!metaKey) return;
    $inpMeta = $(`input[name="meta_${metaKey}"]`);
    if ($inpMeta.length == 0) {
      $inpMeta = $(`#${metaKey}`);
      // console.log("metaKey", $inpMeta);
    }
    $$inpMetaForDedup[metaKey] = $inpMeta;
    // 追加文本到输入框后边
    $inpMeta.after(`<span class="btn gray meta-btn meta-btn-${metaKey}">重复检测</span>`);
    // 封装检测函数
    const checkDedup = function (e) {
      console.log('文本框事件', metaKey, e.type);
      fnRltAddOrReset();
      clearTimeout(t);
      t = setTimeout(function () {
        fnSearch($(`.meta-btn.meta-btn-${metaKey}`));
      }, 1370);
    };
    // 文本内容改变时，检查是否重复
    $inpMeta.change(checkDedup).keyup(checkDedup);
  });
  // console.log("$$inpMetaForDedup", $$inpMetaForDedup);

  // 点击按钮后，检测是否有重复的
  $('.btn.meta-btn').click(function () {
    const $this = $(this);
    fnSearch($this);
  });

  const btnPostConfirm = {
    $btn: $("#btnPost"),
    lock() {
      if (!this.isConfirm()) return;
      this.$btn.addClass("lock");
    },
    unlock() {
      this.$btn.removeClass("lock");
    },
    isConfirm() {
      return confirmLogPost === "1";
    },
    init() {
      const $btn = this.$btn;
      this.$btn.click(() => {
        if ($btn.hasClass("lock")) {
          alert("存在重复项，请检查");
          return false;
        }
      })
    }
  }
  btnPostConfirm.init();

  const obj$btn = {
    $btn: null,
    lock() {
      if (this.isNull$btn()) return;
      this.$btn.data('text', this.$btn.text());
      this.$btn.addClass('disabled');
      this.$btn.text('检测中...');
    },
    unlock() {
      if (this.isNull$btn()) return;
      this.$btn.removeClass('disabled');
      this.$btn.text(this.$btn.data('text'));
    },
    isLock() {
      if (this.isNull$btn()) return false;
      return this.$btn.hasClass('disabled');
    },
    isNull$btn() {
      return this.$btn === null;
    }
  }

  function fnSearch($btn = null) {
    // 如果有按钮，就锁定按钮
    if (obj$btn.isLock()) return;
    // 先判断是否锁定，再赋值按钮
    obj$btn.$btn = $btn;
    obj$btn.lock();
    // 始终执行的回调函数
    const fnAlways = () => {
      setTimeout(() => {
        obj$btn.unlock();
      }, 1370);
    }
    // 查询
    const forSearch = {};
    for (const metaKey in $$inpMetaForDedup) {
      if (Object.hasOwnProperty.call($$inpMetaForDedup, metaKey) && "edtTitle" !== metaKey) {
        const $inpMeta = $$inpMetaForDedup[metaKey];
        const metaValue = $inpMeta.val().trim();
        if (metaValue) {
          forSearch[metaKey] = $inpMeta.val().trim();
        }
      }
    }
    console.log("查询数据", { edtID, forSearch });
    // if (Object.keys(forSearch).length === 0) {
    //   fnAlways();
    //   fnRltAddOrReset("");
    //   btnPostConfirm.unlock();
    //   return;
    // }
    fnAjax({
      edtID,
      edtTitle: _edtTitle(),
      forSearch: Object.values(forSearch).join(','),
    }, (res) => {
      const $res = $(res);
      // console.log(res);
      // console.log($res);
      let strTip = '';
      if (res.indexOf("empty") === -1) {
        strTip = "存在重复项";
        $res.append(`<li><span class="title meta-tip-warn">（****）</span></li>`);
        btnPostConfirm.lock();
      } else {
        strTip = "检查通过";
        $res.addClass('tip-ok');
        btnPostConfirm.unlock();
      }
      $res.prepend(`<li><span class="title">${strTip}：</span></li>`);
      // 添加到页面
      fnRltAddOrReset($res[0]);
      $(".meta-rlt:not(.tip-ok)").flash(4, 370);
      fnAlways();
    }, fnAlways);
  }

  function fnAjax(postData, sucCallback, errCallback) {
    $.ajax({
      type: 'POST',
      url: bloghost + "zb_users/PLUGIN/xnxf_CustomMeta_Ext/find.asp?act=q",
      data: postData,
      success: function (res) {
        sucCallback(res);
      },
      error: function (err) {
        console.log(err);
        errCallback();
      },
    });
  }
});
